package com.fla.millioner;

import com.fla.millioner.ui.support.Cencrypt;
import com.readystatesoftware.sqliteasset.SQLiteAssetHelper;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteQueryBuilder;
import android.util.Log;

public class QuestionService extends SQLiteAssetHelper {
    private static final String DATABASE_NAME = "questions";
    private static final String TABLE = "questions";
    private static final int DATABASE_VERSION = 2;

    public QuestionService(Context context, String storageDir) {
        super(context, DATABASE_NAME, storageDir, null, DATABASE_VERSION);

        // you can use an alternate constructor to specify a database location
        // (such as a folder on the sd card)
        // you must ensure that this folder is available and you have permission
        // to write to it
        // super(context, DATABASE_NAME, context.getExternalFilesDir(null).getAbsolutePath(), null, DATABASE_VERSION);
    }

    public void load() {
        getWritableDatabase();
    }

    public Question getQuestionMarkRead(int level) {
        SQLiteDatabase database = getWritableDatabase();
        SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();

        queryBuilder.setTables(TABLE);

        Cursor c = queryBuilder.query(database, null, "level=" + level, null, null, null, "read_count, RANDOM()", "1");
        c.moveToFirst();

        Question question = new Question();

        question.setId(c.getLong(0));
        question.setQuestion(d(c.getString(1)));
        question.setAnswer1(d(c.getString(2)));
        question.setAnswer2(d(c.getString(3)));
        question.setAnswer3(d(c.getString(4)));
        question.setAnswer4(d(c.getString(5)));
        question.setLevel(c.getInt(6));
        question.setReadCount(c.getInt(7));

        c.close();

        try {
            ContentValues contentValues = new ContentValues();
            contentValues.put("read_count", question.getReadCount() + 1);
            database.update(TABLE, contentValues, "id=" + question.getId(), null);
        }
        catch (SQLiteException e) {
            Log.e("test", "Cannot update read count", e);
        }

        return question;
    }

    private String d(String string) {
        return Cencrypt.decrypt(string, "com.fla.millioner");
    }
}